import { useEffect, useState, useCallback } from 'react';
import { message } from 'antd';
import { getEmployeeAndOrgList } from '@/pages/authoritymanage/usergroupmanage/services';

function updateTreeData(list, key, children) {
  return list.map((node) => {
    if (node.value === key) {
      return { ...node, children };
    }
    if (node.children) {
      return { ...node, children: updateTreeData(node.children, key, children) };
    }
    return node;
  });
}

const useOrgTreeSelect = () => {
  const [treeData, setTreeData] = useState([]);

  useEffect(() => {
    getEmployeeAndOrgList({ parentId: 0 }).then((res) => {
      const { data, code, message: errorMessage } = res;
      if (code === 0) {
        const { childOrgList = [], employeeList = [] } = data || {};
        const orgNodes = childOrgList.map(
          item => ({
            id: item.orgId,
            title: item.orgName,
            value: item.orgId,
            checkable: false,
            selectable: false,
          })
        );
        const employeeNodes = employeeList.map(
          item => ({
            id: item.employeeId,
            title: item.employeeName,
            value: item.employeeId,
            isLeaf: true,
          })
        );
        setTreeData([...orgNodes, ...employeeNodes]);
      } else {
        message.error(errorMessage);
      }
    });
  }, []);

  const onLoadData = useCallback((data) => {
    const { key, children } = data;
    return new Promise((resolve) => {
      if (children) {
        resolve();
        return;
      }
      getEmployeeAndOrgList({ parentId: key }).then((resData) => {
        const { data: childData, code, message: errorMessage } = resData || {};
        if (code === 0) {
          const { childOrgList = [], employeeList = [] } = childData || {};
          const childOrgNodes = childOrgList.map(
            item => ({
              id: item.orgId,
              title: item.orgName,
              value: item.orgId,
              checkable: false,
              selectable: false,
            })
          );
          const childEmployeeNodes = employeeList.map(
            item => ({
              id: item.employeeId,
              title: item.employeeName,
              value: item.employeeId,
              isLeaf: true,
            })
          );
          const newList = updateTreeData(treeData, key, [...childOrgNodes, ...childEmployeeNodes]);
          setTreeData(newList);
          resolve();
        } else {
          message.error(errorMessage);
          resolve();
        }
      });
    });
  }, [treeData]);

  return [treeData, onLoadData];
};

export default useOrgTreeSelect;
